package com.bawei.a2010douyin.ui.tuijian;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bawei.a2010douyin.R;
import com.bawei.a2010douyin.annotation.LoginCheck;
import com.bawei.a2010douyin.base.mvp.BaseFragment;
import com.bawei.a2010douyin.base.mvp.BaseMvpFragment;
import com.bawei.a2010douyin.base.utils.ARouterPath;
import com.bawei.a2010douyin.entity.CommentEntity;
import com.bawei.a2010douyin.entity.VideoEntity;
import com.bawei.a2010douyin.widget.DouYinLinearLayoutManager;
import com.bawei.a2010douyin.widget.VideoRecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;

import java.util.HashMap;
import java.util.List;


public class TuiJianFragment extends BaseMvpFragment<TuiJianContract.ITuiJianView,TuiJianPresenter> implements TuiJianContract.ITuiJianView {
    private VideoRecyclerView rv;
    private VideoAdapter mVideoAdapter;
    private DouYinLinearLayoutManager mDouYinLinearLayoutManager;//上下翻页
    private int video_position;//当前显示item的下标
    private RecyclerView rvComment;
    private CommentAdapter mCommentAdapter;



    @Override
    public int bindLayout() {
        return R.layout.fragment_tui_jian;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        rv = (VideoRecyclerView) findViewById(R.id.rv);
        mVideoAdapter = new VideoAdapter();
        mDouYinLinearLayoutManager = new DouYinLinearLayoutManager(getContext());
        rv.setLayoutManager(mDouYinLinearLayoutManager);
        rv.setAdapter(mVideoAdapter);
        //滑动自动播放
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //1:获得当前下标
                video_position = mDouYinLinearLayoutManager.findFirstVisibleItemPosition();
                //2:根据下标获得视频播放器
                StandardGSYVideoPlayer standardGSYVideoPlayer = (StandardGSYVideoPlayer) mVideoAdapter.getViewByPosition(video_position,R.id.gsy);
                //3:播放
                if(standardGSYVideoPlayer != null){
                    standardGSYVideoPlayer.startPlayLogic();
                }
            }
        });
        //item点击
      //  mVideoAdapter.setOnItemClickListener();
        //设置item子控件的点击事件
        mVideoAdapter.addChildClickViewIds(R.id.iv_add,R.id.iv_dianzan,R.id.ll_zhibo,R.id.iv_share,R.id.iv_comment,R.id.iv_send,R.id.iv_close);
        mVideoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_add://关注
                        guanzhu();
                        break;
                    case R.id.iv_dianzan://点赞
                        dianzan();
                        break;
                    case R.id.ll_zhibo://点击进入直播间
                        zhibo();
                        break;
                    case R.id.iv_share://分享
                        share();
                        break;
                    case R.id.iv_comment://评论
                        comment();
                        break;
                    case R.id.iv_send://发表评论
                        send();
                        break;
                    case R.id.iv_close://关闭评论框
                        close();
                        break;
                }
            }
        });

    }

    /**
     * 关闭评论
     */
    private void close() {
        LinearLayout llComment  = (LinearLayout) mVideoAdapter.getViewByPosition(video_position, R.id.ll_comment);
        llComment.setVisibility(View.GONE);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.out);
        llComment.startAnimation(animation);
        rv.setInterceptor(true);//拦截
    }

    /**
     * 发表评论前判断是否登陆
     * {
     *   "msg": "string",
     *   "videoId": 0
     * }
     */
    @LoginCheck
    private void send() {
        EditText editText = (EditText) mVideoAdapter.getViewByPosition(video_position,R.id.et);//编辑框
        int id = mVideoAdapter.getData().get(video_position).getId();//视频id
        //json请求体
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg",editText.getText().toString());
        map.put("videoId",id);
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        //发起请求
        mPresenter.sendComment(requestBody);
    }

    /**
     * 查看评论
     */
    private void comment() {
        //1:弹出评论框
        LinearLayout llComment  = (LinearLayout) mVideoAdapter.getViewByPosition(video_position, R.id.ll_comment);
        llComment.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.in);
        llComment.startAnimation(animation);
        rv.setInterceptor(false);//不拦截
        //2：初始化列表
        rvComment = (RecyclerView) mVideoAdapter.getViewByPosition(video_position,R.id.rv_comment);
        mCommentAdapter = new CommentAdapter(R.layout.item_comment);
        rvComment.setAdapter(mCommentAdapter);
        rvComment.setLayoutManager(new LinearLayoutManager(getContext()));

        //3：发起网络请求获得评论信息:根据视频id获得评论
        mPresenter.comment(mVideoAdapter.getData().get(video_position).getId());


    }

    /**
     * 分享前判断是否登陆
     */
    @LoginCheck
    private void share() {
        VideoEntity videoEntity = mVideoAdapter.getData().get(video_position);//数据

        UMVideo video =new UMVideo(videoEntity.getVideopath());//视频地址
        video.setTitle(videoEntity.getAuthname());//视频的标题
        UMImage umImage = new UMImage(getActivity(), videoEntity.getHeadpath());//视频的图片
        video.setThumb(umImage);//视频的缩略图
        video.setDescription(videoEntity.getCaption());//视频的描述



        new ShareAction(getActivity())
                .withMedia(video)//分享视频
                .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        Toast.makeText(getActivity(), "分享成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        Toast.makeText(getActivity(), "分享失败"+throwable.getMessage(), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                    }
                })
                .open();
    }

    /**
     * 关注前判断是否登陆
     */
    @LoginCheck
    private void guanzhu() {
        //----生成json数据请求体
        HashMap<String, String> map = new HashMap<>();
        map.put("authname",mVideoAdapter.getData().get(video_position).getAuthname());
        String json = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        mPresenter.guanzhu(requestBody);
    }

    /**
     * 点击进入直播间
     */
    private void zhibo() {
        ARouter.getInstance()
                .build(ARouterPath.ZHIBO_AROUTER_PATH)
                .withSerializable("video",mVideoAdapter.getData().get(video_position))//传值
                .navigation();
    }

    /**
     * 点赞前需要判断是否登陆
     */
    @LoginCheck
    private void dianzan() {
        int id = mVideoAdapter.getData().get(video_position).getId();//视频id
        int dianzan = mVideoAdapter.getData().get(video_position).getDianzan();//是否点赞
        if(dianzan == 0){//点赞
                mPresenter.love(id);
        }else{//取消点赞
            mPresenter.nolove(id);
        }
    }

    @Override
    public TuiJianPresenter createPresenter() {
        return new TuiJianPresenter();
    }

    @Override
    public void initData() {
        mPresenter.video(1,10);
    }
    //展示视频结果
    @Override
    public void showVideo(List<VideoEntity> data) {
        mVideoAdapter.getData().addAll(data);
        mVideoAdapter.notifyDataSetChanged();
    }
    //展示点赞成功结恶果
    @Override
    public void love(String str) {
        ImageView ivDianzan = (ImageView) mVideoAdapter.getViewByPosition(video_position, R.id.iv_dianzan);
        ivDianzan.setImageResource(R.drawable.ic_xihuanred);
        mVideoAdapter.getData().get(video_position).setDianzan(1);//本地数据更新
        //动画：缩放 左右摇摆
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(ivDianzan, "ScaleX", 1, 1.5f, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(ivDianzan, "ScaleY", 1, 1.5f, 1);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(ivDianzan, "Rotation", 0, 30);
        rotation.setInterpolator(new CycleInterpolator(4));//周期差值器

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX,scaleY,rotation);
        animatorSet.setDuration(1500);
        animatorSet.start();

    }
    //展示取消点赞结果
    @Override
    public void nolove(String str) {
        ImageView ivDianzan = (ImageView) mVideoAdapter.getViewByPosition(video_position, R.id.iv_dianzan);
        ivDianzan.setImageResource(R.drawable.ic_xihuan);
        mVideoAdapter.getData().get(video_position).setDianzan(0);//本地数据更新

    }
    //展示关注结果
    @Override
    public void guanzhu(String data) {
        ImageView ivAdd = (ImageView) mVideoAdapter.getViewByPosition(video_position,R.id.iv_add);
//       先变成对勾，背景红色
        ivAdd.setImageResource(R.drawable.ic_duigou);
        ivAdd.setBackground(getResources().getDrawable(R.drawable.shape_white));
        mVideoAdapter.getData().get(video_position).setGuanzhu(1);//本地数据更新
        //动画：消失动画
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(ivAdd, "Alpha", 1, 0);
        objectAnimator.setDuration(1500);
        objectAnimator.start();
        objectAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ivAdd.setVisibility(View.GONE);
            }
        });


    }
    //展示评论数据
    @Override
    public void showComment(List<CommentEntity> data) {
        mCommentAdapter.getData().addAll(data);
        mCommentAdapter.notifyDataSetChanged();
    }
    //展示发表评论结果
    @Override
    public void showSendComment(List<CommentEntity> data) {
        mCommentAdapter.getData().addAll(0,data);//将评论信息放在首行
        mCommentAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getContext()).onActivityResult(requestCode, resultCode, data);
    }
}